using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using DeathReportManagement.Services;

namespace DeathReportManagement.Controllers;

public class AccountController : Controller
{
    private readonly AuthService _authService;
    
    public AccountController(AuthService authService)
    {
        _authService = authService;
    }
    
    [HttpGet]
    public IActionResult Login()
    {
        if (User.Identity?.IsAuthenticated == true)
        {
            return RedirectToAction("Index", "Home");
        }
        
        return View();
    }
    
    [HttpPost]
    public async Task<IActionResult> Login(string doctorCode, string password)
    {
        if (string.IsNullOrWhiteSpace(doctorCode))
        {
            ModelState.AddModelError("", "请输入医生编号");
            return View();
        }
        
        var user = await _authService.AuthenticateAdminAsync(doctorCode, password ?? "");
        
        if (user == null)
        {
            ModelState.AddModelError("", "用户名或密码错误");
            return View();
        }
        
        if (user.Role == "Admin")
        {
            return RedirectToAction("Index", "Admin");
        }
        else
        {
            return RedirectToAction("Index", "DeathReport");
        }
    }
    
    [HttpGet]
    public async Task<IActionResult> DoctorLogin(string doctorCode, string? department = null)
    {
        if (string.IsNullOrWhiteSpace(doctorCode))
        {
            return RedirectToAction("Login");
        }
        
        var user = await _authService.AuthenticateDoctorAsync(doctorCode);
        
        if (user == null)
        {
            TempData["Error"] = "医生编号不存在或已禁用";
            return RedirectToAction("Login");
        }
        
        return RedirectToAction("Create", "DeathReport");
    }
    
    [HttpPost]
    [Authorize]
    public async Task<IActionResult> Logout()
    {
        await _authService.SignOutAsync();
        return RedirectToAction("Login");
    }
}